from app.schemas.chat import ChatCreate, ChatUpdate, Chat
from app.schemas.message import Message
from app.database.connection import get_database
from datetime import datetime
from bson import ObjectId

async def create_chat(chat: ChatCreate) -> Chat:
    """创建聊天"""
    db = get_database()
    
    # 创建聊天文档
    chat_dict = chat.dict()
    chat_dict["created_at"] = datetime.utcnow()
    chat_dict["updated_at"] = datetime.utcnow()
    chat_dict["last_message_id"] = None
    
    # 插入数据库
    result = await db["chats"].insert_one(chat_dict)
    
    # 获取创建的聊天
    created_chat = await db["chats"].find_one({"_id": result.inserted_id})
    
    # 转换为Chat对象
    chat_response = created_chat.copy()
    chat_response["id"] = str(chat_response["_id"])
    # 转换参与者ID为字符串
    chat_response["participants"] = [str(participant) for participant in chat_response["participants"]]
    if chat_response["last_message_id"]:
        chat_response["last_message_id"] = str(chat_response["last_message_id"])
    
    return Chat(**chat_response)

async def get_chat(chat_id: str) -> Chat:
    """获取聊天详情"""
    db = get_database()
    try:
        chat_doc = await db["chats"].find_one({"_id": ObjectId(chat_id)})
        if chat_doc:
            chat_response = chat_doc.copy()
            chat_response["id"] = str(chat_response["_id"])
            # 转换参与者ID为字符串
            chat_response["participants"] = [str(participant) for participant in chat_response["participants"]]
            if chat_response["last_message_id"]:
                chat_response["last_message_id"] = str(chat_response["last_message_id"])
            return Chat(**chat_response)
        return None
    except Exception:
        return None

async def get_user_chats(skip: int = 0, limit: int = 100) -> list[Chat]:
    """获取用户聊天列表"""
    db = get_database()
    chats_cursor = db["chats"].find().skip(skip).limit(limit)
    chats = await chats_cursor.to_list(length=limit)
    
    result = []
    for chat_doc in chats:
        chat_response = chat_doc.copy()
        chat_response["id"] = str(chat_response["_id"])
        # 转换参与者ID为字符串
        chat_response["participants"] = [str(participant) for participant in chat_response["participants"]]
        if chat_response["last_message_id"]:
            chat_response["last_message_id"] = str(chat_response["last_message_id"])
        result.append(Chat(**chat_response))
    
    return result

async def update_chat(chat_id: str, chat_update: ChatUpdate) -> Chat:
    """更新聊天"""
    db = get_database()
    
    # 构建更新字典
    update_data = {k: v for k, v in chat_update.dict().items() if v is not None}
    if not update_data:
        return await get_chat(chat_id)
    
    update_data["updated_at"] = datetime.utcnow()
    
    # 更新数据库
    result = await db["chats"].update_one(
        {"_id": ObjectId(chat_id)},
        {"$set": update_data}
    )
    
    if result.modified_count == 0:
        return None
    
    return await get_chat(chat_id)

async def delete_chat(chat_id: str) -> bool:
    """删除聊天"""
    db = get_database()
    result = await db["chats"].delete_one({"_id": ObjectId(chat_id)})
    return result.deleted_count > 0

async def get_chat_messages(chat_id: str, skip: int = 0, limit: int = 100) -> list[Message]:
    """获取聊天消息记录"""
    db = get_database()
    messages_cursor = db["messages"].find({"chat_id": ObjectId(chat_id)}).skip(skip).limit(limit)
    messages = await messages_cursor.to_list(length=limit)
    
    result = []
    for message_doc in messages:
        message_response = message_doc.copy()
        message_response["id"] = str(message_response["_id"])
        message_response["chat_id"] = str(message_response["chat_id"])
        message_response["sender_id"] = str(message_response["sender_id"])
        result.append(Message(**message_response))
    
    return result